/**
 * @Author: 赵京涛 z19472333952022@163.com
 * @Date: 2024-10-08 09:13:19
 * @LastEditors: 赵京涛 z19472333952022@163.com
 * @LastEditTime: 2024-10-08 09:13:19
 * @projectName: HeBeiHaiYangData
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki
 */
import axios from 'axios'
import { Loading, Message, MessageBox } from 'element-ui'
import errorCode from '@/utils/errorCode'
import { blobValidate, tansParams } from '@/utils/common'
import { saveAs } from 'file-saver'
import store from '@/store'
import { useLocalStorage } from '@/hooks'

let downloadLoadingInstance;
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 150000
})

// request拦截器
service.interceptors.request.use(
  (config) => {
    const userInfo = JSON.parse(useLocalStorage.getItem('userInfo'))
    const hasToken = userInfo && userInfo.userId !== '' ? userInfo.userId : ''
    if (hasToken) {
      config.headers['X-Token'] = hasToken
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    }
    if (config.params) {
      const params = JSON.parse(JSON.stringify(config.params))
      for (const key in params) {
        if (typeof params[key] === 'object') {
          delete params[key]
        }
      }
      config.params = params
    }
    return config
  },
  (error) => {
    // 请求发生错误
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(response => {
    const res = response.data
    if (response.status === 200) {
      if (res.status !== 0) {
        if (res.status === 20) {
          MessageBox.confirm('用户已过期，请重新登录', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
          $('.load-warp').css('z-index', '999')
        } else if (!res.status) {
          return Promise.resolve(res)
        } else {
          Message({
            message: res.msg || 'Error',
            type: 'error',
            duration: 5 * 1000
          })
        }
      } else {
        return Promise.resolve(res)
      }
    } else {
      Message({
        message: res.msg,
        type: 'error',
        duration: 3 * 1000,
        showClose: true
      })
      return Promise.reject(new Error(res.msg))
    }
  },
  error => {
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'error',
      duration: 3 * 1000,
      showClose: true
    })
    return Promise.reject(error)
  }
)

// 通用下载方法
export function download(url, params, filename, config) {
  downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob',
    ...config
  }).then(async (data) => {
    const isBlob = blobValidate(data);
    if (isBlob) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      Message.error(errMsg);
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误，请联系管理员！')
    downloadLoadingInstance.close();
  })
}

export default service
